﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Collections.ObjectModel;
using System.IO;
using SharedLib.DataStructure;

namespace SharedLib.CrossCuttingFramework
{
    public class SimpleDIContainer
    {
        InterfaceClassFilter _interfaceFilter = new InterfaceClassFilter();
        public SimpleDIContainer()
        {
            Initialize();
        }
        

        /// <summary>
        /// Override for customizd initialization operations
        /// </summary>
        protected virtual void Initialize()
        {

        }

        /// <summary>
        /// Create class instance
        /// </summary>
        /// <param name="typeInterface"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        public T CreateInstance<T>(string className) where T : class
        {
            return CreateInstance(typeof(T).FullName, className) as T;
        }

        /// <summary>
        /// Create class instance
        /// </summary>
        /// <param name="interfaceName"></param>
        /// <param name="className"></param>
        /// <returns></returns>
        public object CreateInstance(string interfaceName, string className)
        {
            if (_interfaceFilter.RegisteredClasses.ContainsKey(interfaceName))
            {
                IDictionary<string, Type> classesInSpecifiedInterface = _interfaceFilter.RegisteredClasses[interfaceName];
                if (classesInSpecifiedInterface.ContainsKey(className))
                {
                    Type typeClass = classesInSpecifiedInterface[className];

                    return Activator.CreateInstance(typeClass);
                }
            }
            return null;
        }

        public void LoadPlugins(PluginManager manager)
        {
            _interfaceFilter.RegisterInterface<IPlugin>();
            foreach (Type t in manager.PluginTypes)
            {
                _interfaceFilter.RegisterClass(t);
            }
        }

    }
}
